<!--  -->
<template>
  <div>
    <div v-if="requestError" class="text-c errorPlace">
      <img width="100px" height="100px" :src="require('@/assets/images/pic_neterror.png')" alt="获取数据失败" />
      <div class="color-b font14" style="margin: 10px 0 0 0">
        获取数据失败!
      </div>
      <van-button plain round size="small" color="#7232dd" type="primary" @click="getdetail">点击重试</van-button>
    </div>
    <van-form v-else @submit="submitFromData">
      <van-tabs v-model="active" color="#1989fa" sticky animated line-width="33%" offset-top="50" @click="onClick">
        <van-tab title="基础信息">
          <tabone ref="toMsgs" :isdrawType='isdrawType' :canEdit='canEdit' :titledata='titledata'
            :businessdata='businessdata' :fromdata='fromdata' :showHistory='showHistory' :approveList='approveList'
            :historydata='historydata' :showSQZC='showSQZC' @freshData='freshData($event)' />
        </van-tab>
        <van-tab title="商机信息">
          <tabtwo :canEdit='canEdit' :user='user' :fromdata='fromdata' :canEditbusinessName='canEditbusinessName'
            @freshData='freshData($event)' />
        </van-tab>
      </van-tabs>
      <div class="left_botton" v-if="showMsgBox">
        <button block type="button" @click="toMsgValue()" style="color:#60a9ec; display: inline-block;width:100%;border: 0px solid #60a9ec;border-radius: 15px 0px 0px 15px;
          padding:10px 10px 10px 15px;font-size:13px">意见</button>
      </div>
      <div v-if="todotype == true || toread == true || canEdit == true" class="footer">
        <van-button block type="info" native-type="submit" :disabled="canToNext == true ? false : true"
          style="display: inline-block;width:100%;border: 15px solid #60a9ec;">{{ toNextValue }}</van-button>
      </div>
    </van-form>

  </div>
</template>

<script>
import { getFormDetail, getSupportByPmInsId, getWfLinkTracks, getWfOptMags } from '@/api/dictapi'
import util from "@/assets/js/public";
import tabone from "@/views/xbdetail/tabone"
import tabtwo from "@/views/xbdetail/tabtwo"
import { mapGetters } from "vuex"
import { Notify, Dialog, Toast } from 'vant'

export default {
  data() {
    return {
      active: 0,
      requestError: false,
      params: this.$route.query,
      showHistory: false,
      historydata: {},//已办显示当前办理人
      fromdata: {},//收入确认信息
      approveList: [],//审批意见列表
      titledata: {}, //主单据信息
      businessdata: {}, //商机基础信息
      showMsgBox: true,
      toNextValue: '流转下一步',
      canToNext: true,
      canEditbusinessName: false,
      todotype: false,
      toread: false,
      showSQZC: false,
      canEdit: false,
      isdrawType: false,
      sjlistdata: {}
    }
  },
  computed: {
    ...mapGetters(['user']),
    ...mapGetters(['userinfo'])
  },
  //生命周期--创建完成
  created() {
    console.log("44444444444" + JSON.stringify(this.params))
    if (this.params.pmInsType == null && this.params.processType != null) {
      this.params.pmInsType = this.params.processType
    }
    if (this.params.todoType % 2 == 0) {
      this.showHistory = true;
    }
    if (this.params.isdraw == '1') {
      this.todotype = true;
      this.canEdit = true
      this.isdrawType = true
      this.fromdata.informantDepartment = this.userinfo.belongCompanyName + "\\" + this.userinfo.belongDepartmentName + "\\" + this.userinfo.belongOrgName
      this.fromdata.informantPosition = this.userinfo.authPositions[0].positionName
    } else if (this.params.todoType == '1') {
      this.todotype = true;
      if (this.params.location == 'dict.start') {
        // this.canToNext=false 
        // this.toNextValue='暂不支持该环节,请至PC端办理'
        this.canEdit = true
      } else {
        this.canToNext = true
        this.toNextValue = '流转下一步'
      }
      this.getdetail();
    } else if (this.params.todoType == '3') {
      this.toread = true;
      this.getdetail();
    } else if (this.params.todoType % 2 == 0) {
      this.getdetail();
    }
  },
  //生命周期--挂载完成
  components: {
    tabone,
    tabtwo,
  },
  //方法调用
  methods: {
    freshData(value) {
      console.log("父页面的数据刷新", this.canEdit)
      if (localStorage.getItem('sjlistdata') != '{}' && localStorage.getItem('sjlistdata')) {
        this.sjlistdata = JSON.parse(localStorage.getItem('sjlistdata'))
        console.log("返回后的数据111111" + this.sjlistdata.isConverBusiness)
        localStorage.setItem('sjlistdata', '{}')
        this.fromdata.opportunitiesNumber = this.sjlistdata.businessId
        this.fromdata.opportunitiesName = this.sjlistdata.businessName
        this.fromdata.cities = this.sjlistdata.city
        this.fromdata.county = this.sjlistdata.county
        this.fromdata.informant = (this.sjlistdata.mgrName != null && this.sjlistdata.mgrName != 'null') ? this.sjlistdata.mgrName : ''
        this.fromdata.informantPhone = (this.sjlistdata.mgrBill != null && this.sjlistdata.mgrBill != 'null') ? this.sjlistdata.mgrBill : ''
        this.fromdata.currentSituation = this.sjlistdata.currentSituation
        this.fromdata.dictIntroduction = this.sjlistdata.projectDesc
        this.fromdata.buildContent = this.sjlistdata.projectDesc
        this.fromdata.industryType = this.sjlistdata.industryType
        this.fromdata.withBusiness = this.sjlistdata.withBusiness
        console.log("返回后的数据22222222" + JSON.stringify(this.fromdata))
      }
      if (this.canEdit == true) {
        this.fromdata = value
      }
    },
    onClick(event) {
      console.log("切换tabs:", event)
      //对name进行赋值，此处name值取tabs中集合数据的位置顺序值
      if (event == 0 && this.isdrawType == false) {
        this.showMsgBox = true
      } else {
        this.showMsgBox = false
      }
    },
    toMsgValue() {
      this.$refs.toMsgs.tomsg()
    },
    goBack() {
      this.$router.back(-1) //返回上一页
    },
    onError(result) {
      this.requestError = true;
      Toast.clear();
      Notify(result.message);
    },
    getdetail() {
      Toast.loading({
        message: '加载中',
        forbidClick: false
      });

      getFormDetail(Object.assign(this.params, { userName: this.user.userName }))
        .then((result) => {
          if (!result.data) {
            this.onError(result);
            return;
          }
          if (result.data.data) {
            this.titledata = result.data.data
            if (this.params.location != 'dict.start') {
              this.showSQZC = true
            }
            if (this.params.location != 'dict.start' && this.params.location != 'dict.toStart') {
              if (this.userinfo.belongDepartmentName == '重要客户中心' || this.userinfo.belongDepartmentName == '行业客户拓展中心') {
                if (this.userinfo.belongOrgName == '项目支撑室') {
                  this.showSQZC = true
                } else {
                  this.showSQZC = false
                }
              } else if (this.userinfo.belongCompanyTypeDictValue != '03') {
                this.showSQZC = true
              } else {
                this.showSQZC = false
              }
            }
            if (this.showSQZC == true && this.params.todoType == '1' && this.params.location != 'dict.toStart') {
              Dialog.alert({
                title: '提示',
                message: '如需调整售前支撑信息，请至PC端修改',
              }).then(() => {
                // on close
              });
            }
            this.params.pmInsId = result.data.data.pmInsId;
            this.getSupportByPmInsId();//获取第一步信息
          }

        })
    },
    //获取两个number code
    getSupportByPmInsId() {
      getSupportByPmInsId(this.params)
        .then((result) => {
          Toast.clear();
          if (!result.data) {
            this.onError(result);
            return;
          }
          if (result.data.data) {
            this.fromdata = result.data.data;
          }
          if (this.showHistory == true) {
            this.getWfLinkTracks();
          } else {
            this.getWfOptMags()
          }
        })
    },
    getWfLinkTracks() {
      getWfLinkTracks(Object.assign(this.params), { userName: this.user.userName })
        .then((result) => {
          Toast.clear();
          if (!result.data) {
            Notify(result.message);
            return;
          }
          if (result.data.data) {
            //数据过滤，并生成新的数组
            this.historydata = result.data.data.filter(item => item.CURRENTSTATE == 10)[0]
            if (this.historydata) {
              if (this.historydata.MANAGER) {
                this.showHistory = true;
              } else {
                this.showHistory = false;
              }
            } else {
              this.showHistory = false;
            }
          } else {
            this.showHistory = false;
          }
          this.getWfOptMags()
        })
    },

    getWfOptMags() {
      getWfOptMags(Object.assign(this.params), { userName: this.user.userName })
        .then((result) => {
          if (!result.data) {
            Notify(result.message);
            return;
          }
          this.approveList = result.data.data.reverse();
        })
    },


    // 流转下一步
    onNext() {

      this.params.formData = this.fromdata;
      var formSendData = { "htmlParamMap": {} };
      formSendData.htmlParamMap = this.fromdata;
      formSendData.id = this.titledata.id;
      formSendData.pmInsId = this.titledata.pmInsId;
      formSendData.processType = this.params.pmInsType
      formSendData.workItemId = this.params.workItemId;
      console.log("传给递交页面:", this.params.pmInsType)
      var params1 = {
        kv: {
          currentUserCode: util.encrypt(this.user.userName),
          source: 'MOBILE',
          location: this.params.location,
          processInstId: this.params.processInstId,
          processDefName: this.params.processDefName,
          processType: this.params.pmInsType,
          isClaimFun: '3',
          isClaimCounty: '3',
          isOperateCity: '3',
          isOperateCounties: '3',
          isProvinceConfirm: '3',
          isCityConfirm: '3',
          isSupport: this.fromdata.isSupport,
          isConverBusiness: this.fromdata.isConverBusiness,
          preAmount: this.fromdata.preAmount,
        },
        body: {
          location: this.params.location,
          processInstId: this.params.processInstId,
          processDefName: this.params.processDefName,
          source: 'MOBILE',
        }
      };

      var params2 = {
        kv: {
          "currentUserCode": util.encrypt(this.user.userName),
          "source": 'MOBILE',
          "location": this.params.location,
          "processInstId": this.params.processInstId,
          'processType': this.params.pmInsType,
          'receiptCode': this.params.processInstId
        },
      };
      if (this.fromdata.isSupport == true) {
        params2.kv.provinceSupport = this.fromdata.provinceSupport
      }
      var params3 = {
        kv: {
          "source": 'MOBILE',
          "currentUserCode": util.encrypt(this.user.userName),
          "workItemId": this.params.todoType == 3 ? "" : this.params.workItemId,
          "processInstId": this.params.processInstId,
          "location": this.params.location,
          "notificationId": this.params.todoType == 3 ? this.params.wfnid : ""
        },
      };
      localStorage.setItem('submitPageParam', JSON.stringify({
        getDecisionsUrl: 'decisionAndUser$api$getDecisions',
        getDecisionsParams: params1,
        getUserUrl: 'decisionAndUser$api$getOrgAndUser',
        getUserParams: params2,
        tosubmintUrl: 'applicationFormEnhance$api$startSubmitProcess',
        tosubmintParams: params3,
        formData: formSendData,
        fromMoa: this.params.fromMoa,
        type: this.params.todoType == 3 ? "toRead" : "toDo"
      }));
      this.$router.push(
        {
          name: 'srqrsubmit'
        }
      );
    },
  },

  submitFromData() { //提交流转
    if (this.fromdata.informantPhone != null && this.fromdata.informantPhone != '') {
      const phonePass = this.newUtils.isPhoneNumber(this.fromdata.informantPhone)
      if (!phonePass) return;
    }
    console.log("传给递交页面:", JSON.stringify(this.fromdata))
    if (!this.fromdata.demandPersonnel || !this.fromdata.supportType || !this.fromdata.supportWay
      || !this.fromdata.purchaseWay || !this.fromdata.supportContent) {
      Notify('请选择填写商机信息');
      return;
    }


    this.controlRule(this.params, this.fromdata.projectID, function () {
      this.onNext();
    }.bind(this));

  }
}
</script>
<style scoped>
.errorPlace {
  position: absolute;
  margin-top: -80px;
  top: 50%;
  margin-left: -50px;
  left: 50%;
}
</style>